<template>
    <el-form id="formRender" ref="formRenderRef" v-bind="formConfig" :disabled="disabled" :model="formData"
        label-width="auto" class="form-renderer">
        <component v-for="(element, index) in widgetList" :key="element.id" :is="render.renderComponent(element)"
            :config="element" :index="index" />
    </el-form>
</template>

<script setup>
import { ref, watch, provide, reactive, nextTick, onMounted } from 'vue'
import render from '@/utils/render'
import { executeEventHandler } from '@/utils/eventExecutor'
import { ElMessage } from 'element-plus'

const formRenderRef = ref()

const props = defineProps({
    formJson: {
        type: Object,
        default: () => ({
            formConfig: {},
            widgetList: []
        })
    },
    requestHeaders: {
        type: Object,
        default: () => ({})
    },
    uploadApi: {
        type: String,
        default: ''
    },
    disabled: {
        type: Boolean,
        default: false
    }
})

provide('uploadApi', props.uploadApi)

const formData = ref({})
const widgetList = ref(props.formJson.widgetList || [])
const formConfig = ref(props.formJson.formConfig || {})
// 提供给所有下层组件
provide('designer', render)
provide('formData', formData)
provide('widgetList', widgetList)
provide('formConfig', formConfig)

// 同步表单内容
watch(() => props.formJson, (config) => {
    if (config && config.widgetList) {
        widgetList.value = config.widgetList
    }
    if (config && config.formConfig) {
        formConfig.value = config.formConfig
    }
}, { deep: true, immediate: true })

const requestHeadersRef = ref(props.requestHeaders)
const customWidgetListRef = ref(props.customWidgetList)

// 监听自定义组件列表的变化
watch(() => props.customWidgetList, (data) => {
    if (data) {
        customWidgetListRef.value = data
    }
}, { deep: true, immediate: true })

// 监听请求头的变化
watch(() => props.requestHeaders, (headers) => {
    if (headers) {
        requestHeadersRef.value = headers
        localStorage.setItem('requestHeaders', JSON.stringify(headers))
    }
}, { deep: true, immediate: true })

// 应用表单全局样式，只维护一个 style 标签
const applyGlobalStyle = (styleContent) => {
  let styleEl = document.getElementById('form-global-style')
  if (!styleEl) {
    styleEl = document.createElement('style')
    styleEl.id = 'form-global-style'
    styleEl.type = 'text/css'
    document.head.appendChild(styleEl)
  }
  // 更新 style 内容
  styleEl.textContent = styleContent || ''
}

watch(
    () => formConfig.value.globalStyle,
    (newVal) => {
        applyGlobalStyle(newVal)
    },
    { immediate: true } // 立即执行一次
)

provide('requestHeaders', requestHeadersRef)
provide('customWidgetList', customWidgetListRef)

defineExpose({
    getFormData: async () => {
        try {
            await formRenderRef.value.validate()
            // 检查子表内容是否已经填写
            const subFormNames = render.checkSubFormData(widgetList.value, formData.value)
            if (subFormNames.length != 0) {
                throw new Error(`${subFormNames.join(",")} 内容不能为空！`)
            }
            const data = JSON.parse(JSON.stringify(formData.value))
            return render.getFormFieldData(widgetList.value, data)// 转换数据的字段信息
        } catch (err) {
            throw err
        }
    },
    setFormData: (data) => {
        const idData = render.getFormIdData(widgetList.value, JSON.parse(JSON.stringify(data)))// 保证原始数据不被破坏
        formData.value = reactive({ ...idData })  // 确保响应式
    },
    resetForm: () => {
        formData.value = {}
    },
    setFormJson: (json) => {
        formData.value = {}
        formConfig.value = json.formConfig || {};
        widgetList.value = json.widgetList || [];
    }
})

onMounted(async () => {
    await nextTick()
    executeEventHandler(formConfig.value.events?.onMounted,
        { formConfig: formConfig.value, formData: formData.value, widgetList: widgetList.value }
    )
})
</script>

<style scoped>
.form-renderer {
    padding: 16px;
}
</style>